'''
'''
import urllib.parse
import urllib.request
from urllib import request,parse
from urllib.request import HTTPBasicAuthHandler,HTTPPasswordMgrWithDefaultRealm,build_opener
from urllib.error import URLError
# 使用表单提交的方式调用示例的post接口
def getWithParam():
    data=bytes(urllib.parse.urlencode({'name':'wanglaoer'}),encoding='utf-8')
    resp=urllib.request.urlopen('https://www.httpbin.org/post',data=data,timeout=10)
    print(resp.read().decode('utf-8'))
# 使用requests 类来发送请求
def postWithRequests():
    data=bytes(parse.urlencode({'name':'张三'}),encoding='utf-8')
    header={
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36 Core/1.94.202.400 QQBrowser/11.9.5355.400'
    }
    req=request.Request('https://www.httpbin.org/post',data=data,headers=header,method='POST')
    resp=request.urlopen(req)
    print(resp.read().decode('utf-8'))
# 获取用户的资源需要登录的场景
def getSourceWithAuth():
    username='admin'
    passwd='admin'
    url='https://ssr3.scrape.center/'
    header={
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36 Core/1.94.202.400 QQBrowser/11.9.5355.400'
    }
    p=HTTPPasswordMgrWithDefaultRealm()
    p.add_password(None,url,username,passwd=passwd)
    auth_handler=HTTPBasicAuthHandler(p)
    opener = build_opener(auth_handler)
    try:
        result=opener.open(url)
        html = result.read().decode('utf-8')
        print(html)
    except URLError as e:
        print(e.reason)    


if __name__ =='__main__':
    getSourceWithAuth()
    pass